import axios from "axios";
import router from "@/router";
import {ElMessage} from "element-plus";
const api = axios.create(
    {
        baseURL: "http://localhost:8081", //这里配置的是后端服务提供的接口
        timeout: 1000
    }
);
api.interceptors.request.use(config => {
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

    // 检查本地存储中是否存在用户数据
    let token = localStorage.getItem("token") ? JSON.parse(localStorage.getItem("token")) : null;
    if (token) {
        config.headers['token'] = token;
    }
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
api.interceptors.response.use(
    response => {

        if(response.data.code===401){
            router.push("/login")
            ElMessage.error("请先登录或注册")
        }
        return response;
    },
    error => {
        console.log('err' + error)
        return Promise.reject(error)
    }
)

export default api;